Professor: Bruno Pimentel
Aluno: Gustavo de Melo Oliveira
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import FunctionTransformer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import confusion_matrix
from sklearn.pipeline import Pipeline
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import plotly.express as px
import seaborn as sns
import pandas as pd
import numpy as np
import nltk
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
[nltk_data] Downloading package stopwords to [nltk_data] C:\Users\gust4\AppData\Roaming\nltk_data... [nltk_data] Package stopwords is already up-to-date! [nltk_data] Downloading package punkt to [nltk_data] C:\Users\gust4\AppData\Roaming\nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package wordnet to [nltk_data] C:\Users\gust4\AppData\Roaming\nltk_data... [nltk_data] Package wordnet is already up-to-date!
True
R:
R:
R:
Obs.: Resposta tomando como base que só temos um único perceptron.
R:
R:
dados = {
'Janeiro': {
'Recebidos': 160,
'Processados': 160
},
'Fevereiro': {
'Recebidos': 184,
'Processados': 184
},
'Março': {
'Recebidos': 241,
'Processados': 237
},
'Abril': {
'Recebidos': 149,
'Processados': 148
},
'Maio': {
'Recebidos': 180,
'Processados': 181
},
'Junho': {
'Recebidos': 161,
'Processados': 150
},
'Julho': {
'Recebidos': 132,
'Processados': 123
},
'Agosto': {
'Recebidos': 202,
'Processados': 156
},
'Setembro': {
'Recebidos': 160,
'Processados': 126
},
'Outubro': {
'Recebidos': 139,
'Processados': 104
},
'Novembro': {
'Recebidos': 149,
'Processados': 124
},
'Dezembro': {
'Recebidos': 177,
'Processados': 140
},
}
df = pd.DataFrame(dados)
df
| Janeiro | Fevereiro | Março | Abril | Maio | Junho | Julho | Agosto | Setembro | Outubro | Novembro | Dezembro | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Recebidos | 160 | 184 | 241 | 149 | 180 | 161 | 132 | 202 | 160 | 139 | 149 | 177 |
| Processados | 160 | 184 | 237 | 148 | 181 | 150 | 123 | 156 | 126 | 104 | 124 | 140 |
months = df.columns
fig = go.Figure()
fig.add_trace(go.Bar(
x=months,
y=df[:1].values[0],
name=df.index[0],
marker_color='deepskyblue'
))
fig.add_trace(go.Bar(
x=months,
y=df[1:].values[0],
name=df.index[1],
marker_color='indianred'
))
fig.update_layout(barmode='group', xaxis_tickangle=-45)
fig.show()
dados = {
'Texto': [
'They are novels',
'have you read this book',
'who is the author',
'what are the characters',
'This is how I bought the book',
'I like fictions',
'what is your favorite book',
'This is my book'
],
'Classe': [
'stmt',
'question',
'question',
'question',
'stmt',
'stmt',
'question',
'stmt'
]
}
df = pd.DataFrame(dados)
df['Texto'] = df['Texto'].apply(lambda x: x.lower())
X = df['Texto']
y = df['Classe']
validation = ['what do you mean']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1, stratify=y)
def remove_stopwords(words):
nltk_words = list(nltk.corpus.stopwords.words('english'))
output = [w for w in words if not w in nltk_words]
return output
transformer = FunctionTransformer(remove_stopwords)
pipe = Pipeline(
[
('stop_words', transformer),
('vect', CountVectorizer()),
('clf', MultinomialNB(alpha=0.1))
]
)
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
print('Classificou o texto correto em',round(np.mean(y_pred == y_test)*100,2),'% das vezes.\n')
print(f'Validação:\n{validation[0]}: {pipe.predict(validation)[0]}')
Classificou o texto correto em 0.0 % das vezes. Validação: what do you mean: question
classe = df['Classe'].unique()
mat = confusion_matrix(y_test, y_pred)
fig = sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False, xticklabels=classe, yticklabels=classe)
plt.xlabel('true label')
plt.ylabel('predicted label')
Text(91.68, 0.5, 'predicted label')
pipe = Pipeline(
[
('stop_words', transformer),
('vect', TfidfVectorizer()),
('clf', MultinomialNB(alpha=0.1))
]
)
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
print('Classificou o texto correto em',round(np.mean(y_pred == y_test)*100, 2),'% das vezes.\n')
print(f'Validação:\n{validation[0]}: {pipe.predict(validation)[0]}')
Classificou o texto correto em 50.0 % das vezes. Validação: what do you mean: question
classe = df['Classe'].unique()
mat = confusion_matrix(y_test, y_pred)
fig = sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False, xticklabels=classe, yticklabels=classe)
plt.xlabel('true label')
plt.ylabel('predicted label')
Text(91.68, 0.5, 'predicted label')
R:
df = pd.read_csv("https://raw.githubusercontent.com/bapimentel/Ciencia-de-Dados/master/Dados/Drugs.csv", index_col=0)
df.columns
Index(['value'], dtype='object')
fig = px.line(df, x=df.index, y="value", title='Vendas de Medicamentos')
fig.update_xaxes(rangeslider_visible=True)
fig.show()
R: